#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量将代码文件转换为UTF-8编码（简化版本，不依赖外部库）
"""

import os
from pathlib import Path

def try_read_file(file_path, encodings=['utf-8', 'gbk', 'gb2312', 'big5', 'latin-1', 'cp1252']):
    """尝试用不同编码读取文件"""
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            return content, encoding
        except (UnicodeDecodeError, UnicodeError):
            continue
    return None, None

def convert_to_utf8(file_path):
    """将文件转换为UTF-8编码"""
    try:
        # 尝试读取文件
        content, current_encoding = try_read_file(file_path)
        
        if content is None:
            print(f"无法读取文件: {file_path}")
            return False
            
        print(f"文件: {file_path}")
        print(f"  当前编码: {current_encoding}")
        
        # 如果已经是UTF-8，检查是否需要转换
        if current_encoding.lower() == 'utf-8':
            print(f"  已经是UTF-8编码")
            return True
            
        # 以UTF-8编码保存
        with open(file_path, 'w', encoding='utf-8', newline='') as f:
            f.write(content)
            
        print(f"  已转换为UTF-8编码")
        return True
        
    except Exception as e:
        print(f"转换失败 {file_path}: {e}")
        return False

def main():
    """主函数"""
    # 获取脚本目录
    script_dir = Path(__file__).parent
    scripts_dir = script_dir / "Assets" / "Scripts"
    
    if not scripts_dir.exists():
        print(f"脚本目录不存在: {scripts_dir}")
        return
    
    # 统计信息
    total_files = 0
    converted_files = 0
    failed_files = 0
    
    print("开始转换代码文件为UTF-8编码...")
    print("=" * 50)
    
    # 遍历所有.cs文件
    for cs_file in scripts_dir.rglob("*.cs"):
        total_files += 1
        print(f"\n处理文件 {total_files}: {cs_file.relative_to(script_dir)}")
        
        try:
            success = convert_to_utf8(cs_file)
            if success:
                converted_files += 1
            else:
                failed_files += 1
        except Exception as e:
            print(f"处理文件时出错: {e}")
            failed_files += 1
    
    print("\n" + "=" * 50)
    print("转换完成!")
    print(f"总文件数: {total_files}")
    print(f"成功处理: {converted_files}")
    print(f"失败文件: {failed_files}")

if __name__ == "__main__":
    main()
